#include "alarm.h"
#include <rtthread.h>
#include "miniscope.h"
#include "beep.h"



static void alarm_entry(void *paramter)
{
	float threshold_value;
	
	while(1)
	{
		if (miniscope.wave.wave_frequency >= 1 && miniscope.wave.wave_frequency < 8)
		{
			threshold_value = 40000.0 / (miniscope.wave.wave_frequency * miniscope.wave.wave_frequency * 1000);
			if (miniscope.adc.B_Value > threshold_value)
			{
				BEEP_ON();
			}
			else
			{
				BEEP_OFF();
			}
		}
		else if (miniscope.wave.wave_frequency >= 8 && miniscope.wave.wave_frequency < 25)
		{
			threshold_value = 5000.0 / (miniscope.wave.wave_frequency * 1000);
			if (miniscope.adc.B_Value > threshold_value)
			{
				BEEP_ON();
			}
			else
			{
				BEEP_OFF();
			}
		}
		else if (miniscope.wave.wave_frequency >= 25 && miniscope.wave.wave_frequency < 1200)
		{
			threshold_value = 5.0 / miniscope.wave.wave_frequency;
			if (miniscope.adc.B_Value > threshold_value)
			{
				BEEP_ON();
			}
			else
			{
				BEEP_OFF();
			}
		}
		else if (miniscope.wave.wave_frequency >= 1200 && miniscope.wave.wave_frequency < 2900)
		{
			threshold_value = 4.1 / 1000;
			if (miniscope.adc.B_Value > threshold_value)
			{
				BEEP_ON();
			}
			else
			{
				BEEP_OFF();
			}
		}
		else if (miniscope.wave.wave_frequency >= 2900 && miniscope.wave.wave_frequency <= 100000)
		{
			threshold_value = 12.0 / (miniscope.wave.wave_frequency * 1000);
			if (miniscope.adc.B_Value > threshold_value)
			{
				BEEP_ON();
			}
			else
			{
				BEEP_OFF();
			}
		}
		rt_thread_delay(30);
	}
}


#define   ALARM_THREAD_PRIO             2
#define   ALARM_THREAD_STACK_SIZE       256

void alarm_Task(void)
{
	rt_thread_t alarm_thread;
	
	alarm_thread = rt_thread_create("alarm",
									alarm_entry,
									RT_NULL,
									ALARM_THREAD_STACK_SIZE,
									ALARM_THREAD_PRIO,
									30);
	
	if (alarm_thread != RT_NULL)
	{
		rt_thread_startup(alarm_thread);
	}
}